package com.demo.asyncs;

import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;

import com.demo.bbdd.NTContract;
import com.demo.model.NavigationDataSet;
import com.demo.model.Placemark;

public class ReadKMLAsyncTask extends AsyncTask<Void, Placemark, Void>
		implements KmlParserListener {

	private static final String url35 = "https://maps.google.com/maps/ms?authuser=1&vps=2&hl=ca&ie=UTF8&msa=0&output=kml&msid=209184740038887338333.00048e8217ecb8226ec1b";
	private String[] urls = new String[] { url35 };

	private Context context;

	public ReadKMLAsyncTask(Context context) {
		this.context = context;
	}

	@Override
	protected Void doInBackground(Void... params) {
		try {
			for (String url : urls) {
				final URL aUrl = new URL(url);
				final URLConnection conn = aUrl.openConnection();
				// conn.setReadTimeout(15 * 1000); // timeout for reading the
				// google
				// maps data: 15 secs
				conn.connect();

				/* Get a SAXParser from the SAXPArserFactory. */
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();

				/* Get the XMLReader of the SAXParser we created. */
				XMLReader xr = sp.getXMLReader();

				/* Create a new ContentHandler and apply it to the XML-Reader */
				NavigationSaxHandler navSax2Handler = new NavigationSaxHandler();
				navSax2Handler.setKmlParserListener(this);
				xr.setContentHandler(navSax2Handler);

				/* Parse the xml-data from our URL. */
				xr.parse(new InputSource(aUrl.openStream()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	@Override
	public void OnPointParsed(Placemark place) {

		List<String> coords = Arrays.asList(place.getCoordinates().split(","));

		if (coords.size() >= 2) {
			String united = coords.get(1) + "/" + coords.get(0);

			String hash = Integer.toString(united.hashCode());

			ContentResolver cr = context.getContentResolver();

			Cursor c = cr.query(NTContract.PLACE.URI,
					new String[] { NTContract.PLACE.HASH },
					NTContract.PLACE.HASH + "=?", new String[] { hash }, null);

			if (!(c != null && c.getCount() > 0)) {
				ContentValues values = new ContentValues();
				values.put(NTContract.PLACE.NAME, place.getTitle());
				values.put(NTContract.PLACE.LAT, coords.get(1));
				values.put(NTContract.PLACE.LNG, coords.get(0));
				values.put(NTContract.PLACE.TIME, System.currentTimeMillis());
				values.put(NTContract.PLACE.HASH, hash);

				cr.insert(NTContract.PLACE.URI, values);
			}
		}
	}

	@Override
	public void onFullKmlParsed(NavigationDataSet dataset) {

	}
}
